/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/3/31 0:12
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.datasource;

import com.hyacinth.config.DSType;
import com.hyacinth.constant.Symbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据源管理类
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class DataSourceManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceManager.class);

    private static Map<String, BaseDataSource> dsMap = new HashMap<>();

    private static BaseDataSource dataSource;

    /**
     * 获取数据源管理实例
     */
    public static DataSourceManager getInstance() {
        return getInstance(DSType.HIKARI);
    }

    public static DataSourceManager getInstance(DSType dsType) {
        if (dataSource == null) {
            if (DSType.DRUID == dsType) {
                dataSource = new DataSource4Druid();
            } else if (DSType.HIKARI == dsType){
                dataSource = new DataSource4Hikari();
            }
        }
        return DataSourceManagerHolder.INSTANCE;
    }

    public BaseDataSource getDataSource(String driver, String url, String username, String password) {
        BaseDataSource ds;
        String dbPoolKey = url + Symbol.UNDERLINE + username + Symbol.UNDERLINE + password;
        if (dsMap.containsKey(dbPoolKey)) {
            ds = dsMap.get(dbPoolKey);
        } else {
            dataSource.setDataSource(driver, url, username, password);
            dsMap.put(dbPoolKey, dataSource);
            ds = dataSource;
        }
        return ds;
    }

    public BaseDataSource getDataSource(String driver, String url, String username, String password, int pollSize) {
        BaseDataSource ds;
        String dbPoolKey = url + Symbol.UNDERLINE + username + Symbol.UNDERLINE + password;
        if (dsMap.containsKey(dbPoolKey)) {
            ds = dsMap.get(dbPoolKey);
        } else {
            dataSource.setDataSource(driver, url, username, password, pollSize);
            dsMap.put(dbPoolKey, dataSource);
            ds = dataSource;
        }
        return ds;
    }

    public void removeDataSource(String url, String username, String password) {
        String dbPoolKey = url + Symbol.UNDERLINE + username + Symbol.UNDERLINE + password;
        if (dsMap.containsKey(dbPoolKey)) {
            dsMap.get(dbPoolKey).close();
            dsMap.remove(dbPoolKey);
        }
    }

    private static class DataSourceManagerHolder {
        private static final DataSourceManager INSTANCE = new DataSourceManager();
    }
}
